package cn.admin.remoting.serialize.impl.hessian;

import cn.admin.config.common.lang.enumeration.EnumUtil;
import com.caucho.hessian.io.AbstractDeserializer;
import com.caucho.hessian.io.AbstractHessianInput;

import java.io.IOException;

public class AliEnumDeserializer extends AbstractDeserializer {

    private Class<?> enumType;

    public AliEnumDeserializer(Class<?> cl) {
        try {
            this.enumType = cl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Class<?> getType() {
        return this.enumType;
    }

    public Object readMap(AbstractHessianInput in) throws IOException {

        String name = null;

        while (!in.isEnd()) {
            String key = in.readString();
            if (key.equals("name")) {
                name = in.readString();
            } else {
                in.readObject();
            }
        }
        in.readMapEnd();
        Object obj = this.create(name);
        in.addRef(obj);
        return obj;
    }

    @Override
    public Object readObject(AbstractHessianInput in, String[] fieldNames) throws IOException {
        String name = null;

        for (String fieldName : fieldNames) {
            if ("name".equals(fieldName)) {
                name = in.readString();
            } else {
                in.readObject();
            }
        }
        Object obj = this.create(name);
        in.addRef(obj);
        return obj;
    }

    private Object create(String name) throws IOException {

        if (name == null) {
            throw new IOException(this.enumType.getName() + " expects name.");
        } else {
            return EnumUtil.getEnumByName(this.enumType,name);
        }
    }

}
